package com.dongdongshop.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.dongdongshop.config.AliyunConfig;
import com.dongdongshop.service.AliyunCodeService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AliyunCodeServiceImpl implements AliyunCodeService {

    @Autowired
    private Client client;

    @Value("${aliyun.signName}")
    private String signName;
    @Value("${aliyun.templateCode}")
    private String templateCode;

    @Override
    public String aliyunCode(String phone) {
        String code = RandomStringUtils.randomNumeric(4);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam("{\"sms_code\":\"" + code + "\"}");
        // 复制代码运行请自行打印 API 的返回值
        try {
            client.sendSms(sendSmsRequest);
            return code;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
